package com.sc1905.crane.home.longer.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 描述：上传文件的统一工具类
 *
 * @author longer
 * @create 2019/8/29 11:12
 */
public class UploadUtil {
    // 传入文件对象和当前请求 返回值是随机生成的文件名
    public static String fileUpload(MultipartFile file, HttpServletRequest req) {
        String uploadPath="/upload/";
        String realPath =req.getServletContext().getRealPath(uploadPath);
        File newFile=new File(realPath);
        if(!newFile.exists()){//判断文件不存在
            newFile.mkdirs();//创建目录
        }
        String filename = file.getOriginalFilename();//获取文件名
        String newFileName= UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));//防止文件重名
        File uploadFile = new File(realPath, newFileName);//创建上传文件保存File对象
        try {
            file.transferTo(uploadFile);//将文件上传到指定的路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return (uploadPath+newFileName);
    }
}
